package cn.sanshuilin.kst.mobile.client.controller;

import cn.sanshuilin.kst.mobile.client.common.controller.BaseController;
import cn.sanshuilin.kst.mobile.client.constant.Message;
import cn.sanshuilin.kst.mobile.client.constant.ReturnCode;
import cn.sanshuilin.kst.system.api.exception.base.BusinessException;
import cn.sanshuilin.kst.system.api.service.IMemberService;
import cn.sanshuilin.kst.system.api.service.ISmsService;
import cn.sanshuilin.kst.system.provider.bean.Member;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;

/**
 * @author greenlee
 * @version v1.0
 * @create 创建时间: 2018-01-25 19:58
 * Copyright 2017  by 三水林科技有限公司
 **/
@Validated
@RestController
@RequestMapping("/{version}/service/sms/")
@Api(tags = "短信服务")
public class SmsController extends BaseController {
    @Autowired
    private ISmsService smsService;
    @Autowired
    private IMemberService memberService;

    @PostMapping(value = "send",produces = "application/json; charset=UTF-8")
    @ApiOperation(value = "发送验证码")
    public Map<String, Object> sendMsgs(
            @ApiParam(required = true,value = "版本",defaultValue = "v1") @PathVariable("version") String version,
            @Pattern(regexp = "1(3[0-9]|4[57]|5[0-35-9]|7[01678]|8[0-9])\\d{8}",message = "手机号码格式错误")
            @ApiParam(required = true,value = "手机号") @RequestParam("mobile")String mobile
    ) throws BusinessException {
        //判断是否已经注册了 用户是否注册过了
        Member member = memberService
                ._getMemberByUsername(mobile);
        if (null!=member){
            Map<String, Object> message = new HashMap<>();
            message.put(Message.RETURN_FIELD_CODE, ReturnCode.USER_EXIST);
            message.put(Message.RETURN_FIELD_DATA, "该用户已经存在");
            return message;
        }
        String code = smsService.createRandomCode(6);
        smsService.sendValidCodeToMobile(mobile,code);

        Map<String, Object> message = new HashMap<>();
        message.put(Message.RETURN_FIELD_CODE, ReturnCode.SUCCESS);
        message.put(Message.RETURN_FIELD_DATA, code);
        return message;
    }


}
